package servlet.department;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import imageUtil.Page;
import imageUtil.PageUtil;
import model.Department;
import service.ServiceDAOFactory;

@WebServlet("/department.do")
public class DepartmentServlet extends HttpServlet{

	private static final long serialVersionUID = -6759240939335553142L;
	
	@Override
	protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
		doPost(req,resp);
	}
	
	@SuppressWarnings("rawtypes")
	protected void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
		Map<String,List> datas = new HashMap<String,List>();
		int currentPage = 0;
		String currentPageStr = req.getParameter("currentPage");
		if(currentPageStr == null || "".equals(currentPageStr)){
			currentPage = 1;
		}else{
			currentPage = Integer.parseInt(currentPageStr);
		}
		int totalCount = 0;
		try{
			totalCount = ServiceDAOFactory.getDepartmentService().findByCount();
		}catch(Exception e){
			e.printStackTrace();
		}
		Page page = PageUtil.createPage(5, totalCount,currentPage);
		req.setAttribute("page", page);
		
		initDepartment(datas,page);
		req.setAttribute("datas", datas);
		req.setAttribute("page", page);
		req.getRequestDispatcher("WEB-INF/view/home/bumen.jsp").forward(req, resp);
	}

	@SuppressWarnings("rawtypes")
	private void initDepartment(Map<String, List> datas, Page page) {
		List<Department> reve = new ArrayList<Department>();
		try{
			List<Department> list = ServiceDAOFactory.getDepartmentService().findByAll(page);
			for(Department r : list){
				reve.add(r);
			}
			datas.put("department", reve);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
}
